﻿using DocumentFormat.OpenXml.ExtendedProperties;
using DocumentFormat.OpenXml.Spreadsheet;
using LF.Application.Helpers;
using LF.Common;
using LF.Domain.Entities;
using LF.Domain.Helper;
using LF.Domain.Services;
using LF.Domain.TargetModel;
using LF.Shared.Dtos.Input;
using LF.Shared.Dtos.Out;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Org.BouncyCastle.Utilities;
using System.IO;
using System.Security.Claims;
using System.Security.Cryptography;
using Volo.Abp.ObjectMapping;

namespace LF.Application.Services.Iml
{
    [Authorize]
    public class WeixinService : BaseService, IWeixinService
    {
        IHttpContextAccessor _httpContext;
        
        IAppManagerService _appManager;
        IUserManagerService _userManager;
        IParamConfigManagerService _paramConfigManager;
        
        public WeixinService(IObjectMapper<LFModule> mapper, 
            IHttpContextAccessor httpContext,
             IAppManagerService appManager,
             IUserManagerService userManager,
             IParamConfigManagerService paramConfigManager,
            IGlobalManagerService globalManager) : base(mapper, globalManager)
        {
            _httpContext = httpContext;

            
            _appManager = appManager;
            _userManager = userManager;
            _paramConfigManager = paramConfigManager;
        }   
        object writing = true;
        [AllowAnonymous]
        public async Task<Result> FileUploadAsync()
        {
            var file = _httpContext.HttpContext!.Request.Form.Files.First();
            if (file != null)
            {
                using (var stream = file.OpenReadStream())
                {
                    var md5 = await FileHelper.Md5(stream);
                    if (!string.IsNullOrEmpty(md5))
                    {
                        var path = Path.Combine(LFConfig.FilePath.Path, "weixin");
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        var toPath = Path.Combine(path, md5 + ".png");
                        lock (writing)
                        {
                            if (!File.Exists(toPath))
                            {
                                stream.Seek(0, SeekOrigin.Begin);
                                File.WriteAllBytes(toPath, stream.GetAllBytes());
                            }
                        }
                    }
                    _appManager.Insert(new Domain.Entities.SysFile { Md5 = md5, Name = file.Name });

                    return Ok(md5 ?? "");
                }
            }
            return Error("无图片文件信息");
        }

        [AllowAnonymous]
        public FileContentResult? GetIcon(string openId)
        {
            //FileContentResult? file;
            //var customer = _customerService.GetCustomer(openId);
            //if(customer==null)
            //    return new FileContentResult(new byte[0], "application/octet-stream");
            //using (var stream = FileHelper.Get(customer.Avatar))
            //{
            //    if (stream == null) return new FileContentResult(new byte[0], "application/octet-stream");
            //    byte[] bytes = new byte[stream.Length];
            //    stream.Read(bytes, 0, bytes.Length);
            //    file = new FileContentResult(bytes, "image/png");
                return new FileContentResult([], "image/png");
            
        }

        [AllowAnonymous]
        public Result PostToken(UserWeixinInut userinput)
        {
            var user = _userManager.GetUserByOpenId(userinput.OpenId);
            if (user == null || user.Mobile != userinput.Mobile)
            {
                return Error("验证失败");
            }

            // 1 定义需要的Cliam信息
            var claims = new[]
            {
                new Claim("Id", user.Id.ToString()),
                new Claim("Name", user.RealName),
                new Claim("UserName", user.UserName)
            };
            var token = JwtHelper.Validate(claims);
            return Ok();
        }

  

        [AllowAnonymous]
        public async Task<Result<string?>> GetOpenidAsync(string code)
        {
            var openId = await Helpers.WeixinHelper.GetOpenidAsync(code);
            return Ok<string?>(openId);
        }

       
        [AllowAnonymous]
        public async Task<Result<string?>> GetWxToken()
        {
            var token = await Helpers.WeixinHelper.GetAccessToken();
            return Ok<string?>(token);
        }

        [AllowAnonymous]
        public async Task<Result<UserOut>> GetPhoneAsync(string code)
        {
            var phoneNumber = await Helpers.WeixinHelper.GetPhoneAsync(code);
            
            if (string.IsNullOrEmpty(phoneNumber))
            {
                return Error<UserOut>("获取手机号失败");
            }

            // 根据手机号查找用户，使用 LINQ 查询
            var where = PredicateBuilder.New<User>(true);
            if (!string.IsNullOrEmpty(phoneNumber))
            {

                where = where.And(p => !p.IsDelete && p.Mobile == phoneNumber);
            }

            var user = _globalManager.Get<User>(where);
            
            if (user == null)
            {
                return Error<UserOut>("未找到对应手机号的用户信息");
            }

            var userOut = _mapper.Map<User, UserOut>(user);
            return Ok(userOut);
        }

        [AllowAnonymous]
        public IResult GetWechatEnterpriseAuthUrl(string state)
        {
            var host = _httpContext.HttpContext!.Request.Host;
            var config = LFConfig.QyWeixin;
            #if !DEBUG
            host = LFConfig.ServiceUrl;
            #endif
            var redirectUrl = $"http://{host}/home/wechat_enterprise_callback?state={state}";
            var encodedRedirectUrl = Uri.EscapeDataString(redirectUrl);
            var url = $"https://open.weixin.qq.com/connect/oauth2/authorize?appid={config.WeixinCorpId}&redirect_uri={encodedRedirectUrl}&response_type=code&scope=snsapi_privateinfo&agentid={config.WeixinCorpAgentId}&state=STATE#wechat_redirect";
            return Results.Redirect(url);
        }

        [AllowAnonymous]
        public async Task<IResult> HandleWechatEnterpriseCallbackAsync(string code, string state)
        {
            var token = "fail";
            try
            {
                Console.WriteLine($"开始处理企业微信回调，code: {code}, state: {state}");
                
                // 使用企业微信授权码获取用户信息
                var userInfo = await QyWeixinHelper.GetUserInfoByCodeAsync(code).ConfigureAwait(false);
                Console.WriteLine($"获取用户信息结果: {userInfo?.UserId ?? "null"}");
                
                if (userInfo != null && !string.IsNullOrEmpty(userInfo.UserId))
                {
                    // 根据企业微信UserId查找系统用户
                    var user = _userManager.GetUserByQyWeixinId(userInfo.UserId);
                    Console.WriteLine($"查找系统用户结果: {(user != null ? "存在" : "不存在")}");
                    
                    if (user != null)
                    {
                        // 生成JWT token
                        var claims = new[]
                        {
                            new Claim("Id", user.Id.ToString()),
                            new Claim("Name", user.RealName ?? ""),
                            new Claim("UserName", user.UserName ?? "")
                        };
                        token = JwtHelper.Validate(claims);
                        Console.WriteLine($"为现有用户生成token成功");
                    }
                    else
                    {
                        Console.WriteLine($"用户不存在，开始从企业微信获取详细信息...");
                        
                        // 用户为空时，通过UserId从企业微信API查询详细信息并创建新用户
                        var userDetail = await QyWeixinHelper.GetUserDetailAsync(userInfo).ConfigureAwait(false);
                        Console.WriteLine($"获取企业微信用户详情结果: {(userDetail != null ? userDetail.Name : "null")}");
                        
                        if (userDetail != null)
                        {
                            // 获取默认密码参数配置
                            var defaultPwdConfig = _paramConfigManager.GetByKey("default_password");
                            string defaultPwd = defaultPwdConfig != null ? defaultPwdConfig.Value : "Aa12345";
                            Console.WriteLine($"获取默认密码配置: {defaultPwd}");

                            // 创建新用户
                            var newUser = new User
                            {
                                Id = Guid.NewGuid(),
                                UserName = userDetail.UserId, // 用企业微信UserId作为用户名
                                RealName = userDetail.Name,
                                Mobile = userDetail.Mobile,
                                Email = userDetail.Email,
                                Avatar = userDetail.Avatar,
                                Gender = ParseGender(userDetail.Gender),
                                QyWeixinUserId = userDetail.UserId,
                                Password = defaultPwd.ToFastMd5(),
                                Active = true,
                                CreatTime = DateTime.Now,
                                UpdateTime = DateTime.Now
                            };

                            Console.WriteLine($"准备插入新用户: {newUser.UserName}, {newUser.RealName}");

                            // 保存用户到数据库
                            var insertResult = _userManager.Insert(newUser);
                            Console.WriteLine($"用户插入结果: {insertResult}");
                            
                            if (insertResult)
                            {
                                // 生成JWT token
                                var claims = new[]
                                {
                                    new Claim("Id", newUser.Id.ToString()),
                                    new Claim("Name", newUser.RealName ?? ""),
                                    new Claim("UserName", newUser.UserName ?? "")
                                };
                                token = JwtHelper.Validate(claims);
                                Console.WriteLine($"为新用户生成token成功");
                            }
                            else
                            {
                                Console.WriteLine($"用户插入失败");
                            }
                        }
                        else
                        {
                            Console.WriteLine($"未能获取到企业微信用户详情");
                        }
                    }
                }
                else
                {
                    Console.WriteLine($"未能获取到有效的企业微信用户信息");
                }
            }
            catch (Exception ex)
            {
                // 记录异常日志
                Console.WriteLine($"企业微信认证失败: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                token = "fail";
            }

            var result = $"{state}/#/pages/auth/auth?oauth2LoginToken={token}&thirdType=wechat_enterprise";
            Console.WriteLine($"最终返回结果: {result}");
            return Results.Redirect(result);
        }

        /// <summary>
        /// 解析企业微信性别字符串为系统Gender枚举
        /// </summary>
        /// <param name="genderStr">企业微信返回的性别字符串 (1=男性, 2=女性)</param>
        /// <returns>系统Gender枚举值</returns>
        private Gender ParseGender(string genderStr)
        {
            switch (genderStr)
            {
                case "1":
                    return Gender.Male;
                case "2":
                    return Gender.Female;
                default:
                    return Gender.Male; // 默认为男性
            }
        }

    }
}

